package com.ghck.server.controller;

import java.security.Principal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ghck.server.controller.access.ArgIndexForPrintLog;
import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.PatientEvent;
import com.ghck.server.model.PatientEventDay;
import com.ghck.server.model.query.PatientEventQuery;
import com.ghck.server.model.query.TreatmentQuery;
import com.ghck.server.model.request.TreatmentReq;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.model.response.TreatmentRes;
import com.ghck.server.security.AjkUserDetails;
import com.ghck.server.service.PatientEventDayService;
import com.ghck.server.service.PatientEventService;
import com.ghck.server.service.TreatmentService;
import com.ghck.server.utils.AjkUtil;
import com.ghck.server.utils.IntegerUtil;

@RequestMapping("/patient_event")
@RestController
public class PatientEventController {
	Logger logger = LoggerFactory.getLogger(PatientEventController.class);
	@Autowired
	PatientEventService patientEventService;

	@Autowired
	PatientEventDayService patientEventDayService;
	
	@Autowired
	TreatmentService treatmentService;

	/**
	 *就诊记录列表
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/treatment/list", method = RequestMethod.GET)
	public ResultList<TreatmentRes> findMyEasemodAccount(Integer startId,Integer endId,Integer start,Integer limit,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		TreatmentQuery query = new TreatmentQuery();
		query.setStartId(startId);
		query.setStart(start);
		query.setEndId(endId);
		query.setLimit(limit);
		query.setUserId(userId);
		List<TreatmentRes> res = treatmentService.findTreatmentByQuery(query);

		return new ResultList<TreatmentRes>(res);
	}

	/**
	 *添加健康数据
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResultObject<Integer> addPatientEvent(@RequestBody PatientEventDay patient,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		String deviceId = patient.getDeviceId();
		String content = patient.getContent();
		String uuid = patient.getUuid();
		Integer categoryId = patient.getCategoryId();
		Date actionTime = patient.getActionTime();
		if(StringUtils.isEmpty(deviceId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"deviceId不能为空");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(content)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"content不能为空");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(uuid)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"uuid不能为空");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		if(categoryId==null || categoryId<=0 || categoryId>6){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"categoryId为空或超出范围");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		if(actionTime==null){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"actionTime不能为空");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		patient.setUserId(userId);

		Integer peId =  patientEventService.insertPatientEvent(patient);

		return new ResultObject<>(peId);

	}
	
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/batch_add", method = RequestMethod.POST)
	public ResultObject<Integer> addPatientEvent(@RequestBody PatientEventDay[] patients,Principal principal){
		Integer peId = 0;
		if (ArrayUtils.isNotEmpty(patients)) {
			for (PatientEventDay patient : patients) {
				Integer userId = Integer.parseInt(principal.getName());
				String deviceId = patient.getDeviceId();
				String content = patient.getContent();
				String uuid = patient.getUuid();
				Integer categoryId = patient.getCategoryId();
				Date actionTime = patient.getActionTime();
				if(StringUtils.isEmpty(deviceId)){
					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"deviceId不能为空");
					logger.info("添加健康数据",exception);
					continue;
					//throw exception;
				}
				if(StringUtils.isEmpty(content)){
					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"content不能为空");
					logger.info("添加健康数据",exception);
					continue;
					//throw exception;
				}
				if(StringUtils.isEmpty(uuid)){
					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"uuid不能为空");
					logger.info("添加健康数据",exception);
					throw exception;
				}
				if(categoryId==null || categoryId<=0 || categoryId>6){
					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"categoryId为空或超出范围");
					logger.info("添加健康数据",exception);
					continue;
					//throw exception;
				}
				if(actionTime==null){
					GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"actionTime不能为空");
					logger.info("添加健康数据",exception);
					continue;
					//throw exception;
				}
				patient.setUserId(userId);

				peId =  patientEventService.insertPatientEvent(patient);
			}
		}
		return new ResultObject<>(peId);

	}

	/**
	 * 修改健康数据
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/modify_patient_event/{patientEventId}", method = RequestMethod.PUT)
	public ResultObject<Integer> modifyMyPatientEvent(@RequestBody PatientEventDay patientEvent,@PathVariable("patientEventId") Integer patientEventId,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());

		if(!IntegerUtil.isPositiveInteger(patientEventId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"patientEventId必须是正整数");
			logger.info("添加健康数据",exception);
			throw exception;
		}

		patientEvent.setId(patientEventId);
		patientEvent.setUserId(userId);

		patientEventService.updatePatientEvent(patientEvent);

		return new ResultObject<>(patientEventId);
	}



	/**
	 *添加就诊数据
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/treatment", method = RequestMethod.POST,consumes="multipart/form-data")
	public ResultObject<Integer> addTreatmentReq(TreatmentReq treatmentReq,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		treatmentReq.setUserId(userId);
		treatmentReq.setInUsed(1);
		String hospitalName = treatmentReq.getHospitalName();
		Long actionTime = treatmentReq.getActionTimeTs();
		if(StringUtils.isEmpty(hospitalName)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"医院不能为空");
			logger.info("添加就诊数据",exception);
			throw exception;
		}
		if(actionTime==null){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"就诊时间不能为空");
			logger.info("添加就诊数据",exception);
			throw exception;
		}
		Integer id = treatmentService.insertTreatment(treatmentReq);
		return new ResultObject<>(id);
	}

	/**
	 *修改就诊数据
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/treatment/{treatmentId}", method = RequestMethod.PUT,consumes="multipart/form-data")
	public ResultObject<Integer> modifyTreatmentReq(TreatmentReq treatmentReq,@PathVariable("treatmentId") Integer treatmentId,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		treatmentReq.setId(treatmentId);
		treatmentReq.setUserId(userId);
		treatmentReq.setInUsed(1);
		if(!IntegerUtil.isPositiveInteger(treatmentId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"treatmentId必须是正整数");
			logger.info("修改就诊数据",exception);
			throw exception;
		}
		Integer id = treatmentService.updateTreatment(treatmentReq);
		return new ResultObject<>(id);
	}


	/**
	 *血压周期表
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/week_blood_press", method = RequestMethod.GET)
	public ResultList<PatientEventDay> findWeekBloodPress(Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		List<PatientEventDay> list = patientEventDayService.findWeekBloodPress(userId);
		return new ResultList<>(list);
	}

	/**
	 *血压周期表
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResultList<PatientEvent> findMyPatientEvent(
			Integer categoryId,
			Long startTs,
			Long endTs,Integer startId,Integer endId,Integer start,Integer limit,Principal principal){
		AjkUserDetails userDetails = AjkUtil.getUserDetails(principal);
		if(userDetails == null){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		PatientEventQuery query = new PatientEventQuery();
		query.setStartId(startId);
		query.setStart(start);
		query.setEndId(endId);
		query.setLimit(limit);
		query.setUserId(userId);
		if(startTs == null ){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "起始时间不能为空");
		}
		query.setStartTime(new Date(startTs));
		if(endTs == null){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "终止时间不能为空");
		}
		query.setEndTime(new Date(endTs));
		List<PatientEvent> list = patientEventService.findPatientEventByQuery(query);
		return new ResultList<>(list);
	}

}
